package cn.shanke.torrentmanagerserver.service;

import cn.shanke.torrentmanagerserver.btclient.model.TmTorrentInfoSimple;
import cn.shanke.torrentmanagerserver.dao.TorrentMapper;
import cn.shanke.torrentmanagerserver.model.BTSite;
import cn.shanke.torrentmanagerserver.model.Category;
import cn.shanke.torrentmanagerserver.model.Torrent;
import cn.shanke.torrentmanagerserver.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional
public class TorrentService extends ServiceImpl<TorrentMapper, Torrent> {

    @Transactional
    public void syncOne(TmTorrentInfoSimple ttis, Long clientid, List<BTSite> sites, List<Category> categories) {
        Torrent model =  super.getOne(new QueryWrapper<Torrent>().lambda().eq(Torrent::getHashString, ttis.getHashString()).eq(Torrent::getClientid,clientid));
        if (model != null) {
            // 种子已存在 同一客户端，种子的hash相同
            String name = !StringUtils.hasText(ttis.getName())?ttis.getName():ttis.getHashString();
            if (StringUtils.hasText(model.getName())) {
                model.setName(name);
            }
            model.setBtid(ttis.getId());
            model.setHashString(ttis.getHashString());
            model.setBtname(name);
            model.setStatus(Torrent.STATUS_LINKED);
            Long siteid = null;
            if (!sites.isEmpty() && !ttis.getTrackers().isEmpty()
                    && (siteid = guessSiteIdWithUrl(ttis.getTrackers().get(0).getAnnounce(), sites)) != null
            ) {
                model.setSiteid(siteid);
            }
            Long categoryid = null;
            if (!categories.isEmpty()
                    && (categoryid = guessCategoryIdWithUrl(ttis.getDownloadDir(), categories)) != null
            ) {
                model.setCategoryid(categoryid);
            }
            super.updateById(model);
        } else {
            model = new Torrent();
            model.setAddtime(System.currentTimeMillis());
            model.setName(ttis.getName());
            model.setAddress(ttis.getMagnetLink());
            model.setBtid(ttis.getId());
            model.setHashString(ttis.getHashString());
            model.setBtname(ttis.getName());
            model.setStatus(Torrent.STATUS_LINKED);
            model.setClientid(clientid);
            Long siteid = null;
            if (!sites.isEmpty() && !ttis.getTrackers().isEmpty()
                    && (siteid = guessSiteIdWithUrl(ttis.getTrackers().get(0).getAnnounce(), sites)) != null
            ) {
                model.setSiteid(siteid);
            }
            Long categoryid = null;
            if (!categories.isEmpty()
                    && (categoryid = guessCategoryIdWithUrl(ttis.getDownloadDir(), categories)) != null
            ) {
                model.setCategoryid(categoryid);
            }
            super.save(model);
        }
    }

    private Long guessSiteIdWithUrl(String url, List<BTSite> sites){
        String domain = StringUtil.getDomainInUrl(url);
        for (int i = 0; i < sites.size(); i++) {
            if (!StringUtils.hasText(sites.get(i).getAddress()) && sites.get(i).getAddress().indexOf(domain)>=0) {
                return sites.get(i).getId();
            }
        }
        return null;
    }

    private Long guessCategoryIdWithUrl(String downloadDir, List<Category> categories){
        for (int i = 0; i < categories.size(); i++) {
            if (!StringUtils.hasText(categories.get(i).getFolder()) && downloadDir.indexOf(categories.get(i).getFolder())>=0) {
//                System.out.println(downloadDir+ ">>>" + categories.get(i).getFolder());
                return categories.get(i).getId();
            }
        }
        return null;
    }
}
